package com.tongzhan.service;

import com.alibaba.fastjson.JSON;
import com.tongzhan.base.BaseCriteria;
import com.tongzhan.base.BaseShareService;
import com.tongzhan.base.Return;
import com.tongzhan.entity.User;
import com.tongzhan.entity.religion.Duties;
import com.tongzhan.repository.UserRepository;
import com.tongzhan.repository.religion.DutiesRepository;
import com.tongzhan.utils.JwtUtil;
import com.tongzhan.utils.ThreadLocalUtil;
import com.tongzhan.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.*;


@Service
public class UserService extends BaseShareService {

    @Autowired
    public UserRepository userRepository;
    @Autowired
    public DutiesRepository dutiesRepository;

    /**
     * 云上统战后台登录
     *
     * @param response
     * @param username
     * @param password
     * @return
     */
    public Return login(HttpServletResponse response, String username, String password) {
        //查询条件
        Query query = new Query();
        query.addCriteria(Criteria.where("UserName").is(username)
                .and("PassWord").is(password).and("IsDelete").is(0));
        User user = userRepository.findOne(query);
        if (user == null) {
            return new Return(Return.FAIL, "用户名或密码错误");
        }

        //FIXME 云上统战主页只有统战部、党派工商科、镇街道、社区、基层大统战、侨务工作科、民宗局才能访问该页面
        if ("00".equals(user.getDutiesCode())
                || "01".equals(user.getDutiesCode())
                || "11".equals(user.getDutiesCode())
                || "21".equals(user.getDutiesCode())
                || "31".equals(user.getDutiesCode())
                || "t1".equals(user.getDutiesCode())
                || "z1".equals(user.getDutiesCode())
                || "c1".equals(user.getDutiesCode())
        ) {
            //封装返回数据
            Map<String, Object> map = new HashMap<>();
            map.put("userInfo", user);
            //基于工具类生成jwt令牌
            String token = JwtUtil.createJWT(UUID.randomUUID().toString(), JSON.toJSONString(user), null);
            map.put("token", token);
            //将token放在响应头
            response.setHeader(JwtUtil.AUTH_HEADER_KEY, token);
            return new Return(map);
        }
        return new Return(Return.FAIL, "当前用户无权限登录");
    }


    public List<Duties> userDutyList() {
        List<Duties> list = dutiesRepository.find(new Query().addCriteria(BaseCriteria.where("DutiesCode").in(Arrays.asList("t1", "01", "11", "21", "31", "z1", "c1"))), null);
        return list;
    }

    /**
     * 根据用户名查询人员是否存在
     *
     * @param userName
     * @param type
     * @return
     */
    public Long findUserByName(String userName, Integer type) {
        long count = userRepository.count(new Query().addCriteria(BaseCriteria.where("userName").is(userName).and("isDelete").is(0).and("type").is(type)));
        return count;
    }

    /**
     * 新增用户
     *
     * @param user
     * @return
     */
    public Return addUser(User user) {
        //判断名称是否重复
        User judgeUser
                = userRepository.findOne(new Query().addCriteria(Criteria.where("UserName").is(user.getUserName())
                .and("IsDelete").is(0)));
        if (judgeUser != null) {
            return new Return(Return.FAIL, "该用户名已被注册");
        }
        user.setCreateTime(LocalDateTime.now());
        user.setIsDelete(0);
        if ("t1".equals(user.getDutiesCode())) {
            //统战部
            user.setType(0);
        } else if ("z1".equals(user.getDutiesCode())) {
            //镇街道
            user.setType(5);
        } else if ("c1".equals(user.getDutiesCode())) {
            //村社区
            user.setType(6);
        } else {
            user.setType(Integer.valueOf(user.getDutiesCode().substring(0, 1)));
        }
        User save = userRepository.save(user);
        if (save != null) {
            return Return.getSuccessResult("新增成功!");
        }
        return Return.getErrorResult("新增失败!");
    }

    /**
     * 根据用户id查询用户详信息
     *
     * @param userId
     * @return
     */
    public User findUserById(String userId) {
        User user = userRepository.findOne(new Query().addCriteria(BaseCriteria.where("UserId").is(userId).and("IsDelete").is(0)));
        return user;
    }

    /**
     * 修改密码
     *
     * @param userId
     * @param newPassword
     * @return
     */
    public long changePassword(String userId, String newPassword) {
        User user = findUserById(userId);
        user.setPassWord(newPassword);
        user.setUpdateTime(LocalDateTime.now());
        long l = userRepository.updateByPrimaryKeySelective(user);
        if (l > 0) {
            return 1;
        }
        return 0;
    }

    /**
     * 逻辑删除用户
     *
     * @param userId
     * @return
     */
    public long delUser(String userId) {
        User user = findUserById(userId);
        if (user != null) {
            user.setIsDelete(1);
            long l = userRepository.updateByPrimaryKeySelective(user);
            if (l > 0) {
                return 1;
            }
        }
        return 0;
    }

    public Map<String, Object> getUserList(Integer page, Integer size, Integer type) {
        Map<String, Object> resultMap = new HashMap<>();
        List<UserVo> resultList = new ArrayList<>();
        PageRequest pof = PageRequest.of(page, size, Sort.Direction.DESC, "CreateTime");
        String dutiesCode = "";
        switch (type) {
            case 0:
                dutiesCode = "t1";
                break;
            case 1:
                dutiesCode = "11";
                break;
            case 2:
                dutiesCode = "21";
                break;
            case 3:
                dutiesCode = "31";
                break;
            case 4:
                dutiesCode = "01";
                break;
            case 5:
                dutiesCode = "z1";
                break;
            case 6:
                dutiesCode = "c1";
                break;
        }
        //type 1-党派 2-侨台 3-乡贤 4-宗教 0-统战部 5-镇街道 6-村社区
        //查询条件
        Query query = new Query().addCriteria(BaseCriteria.where("isDelete").is(0).and("type").is(type).and("dutiesCode").is(dutiesCode));
        if (ThreadLocalUtil.getThreadLocal().getDutiesCode().equals(ThreadLocalUtil.STREET_CODE)) {
            query.addCriteria(BaseCriteria.where("streetCode").like(ThreadLocalUtil.getThreadLocal().getStreetCode()));
        }
        if (ThreadLocalUtil.getThreadLocal().getDutiesCode().equals(ThreadLocalUtil.VILLAGE_CODE)) {
            query.addCriteria(BaseCriteria.where("villageCode").like(ThreadLocalUtil.getThreadLocal().getVillageCode()));
        }
        Page<User> pageUserList = userRepository.findPage(query, pof);
        for (User user : pageUserList.getContent()) {
            UserVo userVo = new UserVo();
            userVo.setUserId(user.getUserId());
            userVo.setDutiyName(user.getDuties());
            userVo.setRealName(user.getRealName());
            userVo.setUrl(user.getPicture());
            userVo.setUserName(user.getUserName());
            userVo.setTime(user.getCreateTime());
            resultList.add(userVo);
        }
        resultMap.put("total", pageUserList.getTotalElements());
        resultMap.put("list", resultList);
        resultMap.put("totalpage", pageUserList.getTotalPages());
        return resultMap;
    }

    /**
     * 更新用户信息
     *
     * @param realName
     * @param duties
     * @param userId
     * @param phone
     * @return
     */
    public long updateUser(String realName, String duties, String userId, String phone) {
        User user = findUserById(userId);
        if (user != null) {
            user.setRealName(realName);
            user.setDuties(duties);
            user.setTelephone(phone);
            long l = userRepository.updateByPrimaryKeySelective(user);
            if (l >= 0) {
                return 1;
            } else {
                return 0;
            }
        }
        return 0;
    }

}

